package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.SelfUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 身份验证
 * Created by ivany on 2016/1/15.
 */
public class AuthenticationActivity extends BaseActivity implements TextWatcher, View.OnClickListener {

    private EditText mEt_Code,mEt_phone;
    private Button mBtn_Next, mBtn_getVerifyCode;

    private String mCode;
    private TimeCount mTimeCount;
    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpwd);
        Tools.changeSystemBar(this);
        setTitle("验证身份");
        initViews();
    }

    @Override
    public void findViewByIds() {
//        mEt_Phone = (EditText) findViewById(R.id.edt_phone);
        mEt_Code = (EditText) findViewById(R.id.edt_getcode);
        mBtn_Next = (Button) findViewById(R.id.btn_forget_next);
        mBtn_getVerifyCode = (Button) findViewById(R.id.btn_getcode);
        mEt_phone = (EditText) findViewById(R.id.edt_phone);
        mEt_phone.setEnabled(false);
        String phone = SPHelper.getTmPhone();
        if (phone != null && !"".equals(phone)) {
            StringBuffer showPhone = new StringBuffer();
            showPhone.append(phone.substring(0, 3)).append("****").append(phone.substring(7));
            mEt_phone.setText(showPhone.toString());
        }
    }

    @Override
    public void initListener() {
//        mEt_Phone.addTextChangedListener(this);
        mEt_Code.addTextChangedListener(this);
        mBtn_Next.setOnClickListener(this);
        mBtn_getVerifyCode.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mLoadingDialog = new LoadingDialog(this);
        mTimeCount = new TimeCount(this, 60000, 1000);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
//        String phone = mEt_Phone.getText().toString();
        String code = mEt_Code.getText().toString();
        if (code != null && !"".equals(code)) {
            mBtn_Next.setEnabled(true);
            mBtn_Next.setAlpha(1.0f);
        } else {
            mBtn_Next.setAlpha(0.5f);
            mBtn_Next.setEnabled(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_getcode:
//                String phone = mEt_Phone.getText().toString();
//                if (phone == null) {
//                    showMsg("请先输入手机号码");
//                } else if (!SelfUtils.isMobileNO(phone)) {
//                    showMsg("手机号码非法,请重新输入");
//                } else {
                mLoadingDialog.setMsg("正在获取验证码");
                mLoadingDialog.show();
                getVerifyCode(SPHelper.getTmPhone());
//                }
                break;
            case R.id.btn_forget_next:
                String code = mEt_Code.getText().toString();
                if (mCode == null) {
                    showMsg("请先获取验证码");
                } else {
                    if (code == null) {
                        showMsg("请输入验证码");
                    } else if (!code.equals(mCode)) {
                        showMsg("验证码错误,请重新输入");
                    } else {
                        Intent intent = new Intent(AuthenticationActivity.this, ResetPaymentCodeActivity.class);
                        startActivityForResult(intent, Constant.RESET_PAYMENTCODE_REQUEST);
                    }
                }
                break;
        }

    }

    //获取验证码
    private void getVerifyCode(String phone) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("type", "2");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "getVerfiyCode response :" + responseInfo.result);
                mLoadingDialog.dismiss();
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取验证码失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            mTimeCount.start();
                            String result = root.getString("result");
                            mCode = result;
                        }
                        String msg = root.getString("message");
                        showMsg(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析失败");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.RESET_PAYMENTCODE_REQUEST) {
            if (resultCode == Constant.RESET_PAYMENTCODE_RESULT) {
                finish();
            }
        }
    }

    /**
     * 时间计时类
     */
    class TimeCount extends CountDownTimer {
        Activity activity;

        public TimeCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }

        /**
         * 计时过程
         *
         * @param millisUntilFinished
         */
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            mBtn_getVerifyCode.setClickable(false);
            mBtn_getVerifyCode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_timecount_bg));
            mBtn_getVerifyCode.setTextColor(getResources().getColor(R.color.textcolor_3));
            mBtn_getVerifyCode.setText(millisUntilFinished / 1000 + "S后重发");
        }

        /**
         * 计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            mBtn_getVerifyCode.setText(R.string.register_get_code);
            mBtn_getVerifyCode.setClickable(true);
            mBtn_getVerifyCode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_bg));
            mBtn_getVerifyCode.setTextColor(getResources().getColor(R.color.bg_button_normal));

        }
    }
}
